<template>
    <section class="normalDistribution">
        <div id="cityNormalDistribution" class="normalDistributionChart" ></div>
        <div id="townNormalDistribution" class="normalDistributionChart" ></div>
    </section>
</template>

<script>
export default {
    name: "NormalDistribution",
    props:{
        taskYear:{
            type:String,
        }
    },
    data(){
        return{
            allList:[],
            cityAvg:0,/*全市平均数*/
            xList:[],/*横坐标*/
        }
    },
    methods:{
        /*去重*/
        getUnique(data){
            let temp = [];
            data.forEach(item => {
                temp.push(parseFloat(item).toFixed(0));
            });
            return Array.from(new Set(temp));
        },
        /*处理初始化数据*/
        handleData(list){
            let temp = this.getUnique(list);
            this.xList.forEach((item,index)=>{
                if(item!=temp[index]){
                    temp.splice(index,0,null);
                }
            });
            return temp;
        },
        /*正态分布计算公式*/
        getDataResult(x,avg,a){
            return  (1 / Math.sqrt(2 * Math.PI) * a) * Math.exp( -1 * ((parseFloat(x)*1000-avg*1000) * (parseFloat(x)*1000-avg*1000)/1000000) / (2 * a * a));
        },
        initData(list){
            let temp = [];
            /*方差*/
            let avg =  this.getAvg(list);
            let deviations = this.getSum(this.getSquare(list.map(function(x){return (parseFloat(x)*1000-avg*1000)/1000;})))/list.length;
            /*标准差*/
            let stddev = Math.sqrt(deviations);
            this.handleData(list).forEach(item => {
                if(item!=null){
                    temp.push(this.getDataResult(item,avg,stddev));
                }else{
                    temp.push(null);
                }
            });
            return temp;
        },
        /*求和*/
        getSum(data){
            let sum = 0;
            data.forEach(item=>{
                sum = (parseFloat(item)*1000 + sum*1000)/1000;
            });
            return sum;
        },
        getSquare(data){
            let tempList = [];
            data.forEach(item=>{
                tempList.push(item*item);
            });
            return tempList;
        },
        /*全市平均分*/
        getAvg(data){
            let sum = 0;
            data.forEach(item=>{
                sum = sum + parseFloat(item);
            });
            return sum/data.length
        },
        handleChartsData(){
            let yTownData = [];
            let townLegend = [];
            let yCityData = [];
            let cityLegend = [];
            /*横坐标*/
            this.xList = this.getUnique(this.allList['全市']);
            /*全市平均数*/
            this.cityAvg =  this.getAvg(this.allList['全市']);
            for (let tempObj in this.allList){
                if (tempObj=='全市'){
                    cityLegend.push(tempObj);
                    yCityData.push({name:tempObj, type: 'line', stack:tempObj, symbolSize: 1,smooth: true,connectNulls: true,
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        {offset: 0, color: 'red'},
                                        {offset: 0.5, color: 'pink'},
                                        {offset: 1, color: '#ffffff'}
                                    ]
                                )
                            }
                        },
                        itemStyle: {
                            normal: {
                                label: {
                                    position:[2,-5],
                                    show: true,
                                    formatter:function(params){
                                        if (params.dataIndex==2){
                                            return params.seriesName
                                        }else{
                                            return ''
                                        }
                                    }
                                }}},
                        data:this.initData(this.allList[tempObj])});
                }else{
                    townLegend.push(tempObj);
                    let townData = this.initData(this.allList[tempObj]);
                    let labelIndex = 0;
                    let tempIndex = 0;
                    for(let i=0;i<townData.length;i++){
                        if(townData[i]!=null){
                            tempIndex++;
                        }
                        if(tempIndex==2){
                            labelIndex = i;
                            break;
                        }
                    }
                    this.$nextTick(()=>{
                        yTownData.push({name:tempObj, type: 'line', stack:tempObj, symbolSize: 1,smooth: true,connectNulls: true,
                            itemStyle: {
                                normal: {
                                    label: {
                                        position:[2,-5],
                                        show: true,
                                        formatter:function(params){
                                            if(params.dataIndex==labelIndex){
                                                return params.seriesName
                                            }else{
                                                return ''
                                            }
                                        }
                                    }}},
                            data:townData});
                    })
                }
            }
            this.$nextTick(()=>{
                this.showCharts('townNormalDistribution',yTownData,this.xList,yTownData);
                this.showCharts('cityNormalDistribution',cityLegend,this.xList,yCityData);
            })
        },
        showCharts(chartsId,legend,xData,yData){
            let chart = echarts.init(document.getElementById(chartsId));
            let option = {
                animationDuration: 1500,
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    data: legend
                },
                grid: {
                    left: '3%',
                    right: '7%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xData,
                    axisPointer: {
                        type: 'shadow'
                    },
                    axisLabel: {
                        interval:0,
                        rotate:35
                    },
                    name:'分数',
                },
                yAxis: {
                    type: 'value',
                    scale:true,
                },
                series:  yData
            };
            chart.setOption(option);
            // chart.resize();
        },
        getData(taskYear){
            let path = `/identity/kPIVillageStatistics/getTotalScore?taskYear=${taskYear}`;
            this.$http('GET', path, false).then(data => {
                if(data){
                    this.allList = data;
                    this.$emit('hasResult', true);
                    this.$nextTick(()=>{
                        this.handleChartsData();
                    })
                } else {
                    this.$emit('hasResult', false);
                }
            })
        }
    },
    watch:{
        'taskYear':{
            immediate: true,
            handler:function () {
                this.getData(this.taskYear);
            }
        }
    },
}
</script>

<style scoped>
    .normalDistribution{
        display: flex;
    }
    .normalDistribution .normalDistributionChart{
        flex:1;
        height: 500px;
    }

</style>
